package com.alex.springboot02web.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Controller
public class ParameterMapAndModelTestController {

    @GetMapping("/test/map_and_model")
    public String test01(Map<String, Object> map,
                         Model model,
                         HttpServletRequest request,
                         HttpServletResponse response) {
        map.put("name", "alex");
        model.addAttribute("age", 12);
        request.setAttribute("gender", "male");

        Cookie cookie = new Cookie("uid", "alexzshl");
        cookie.setDomain("localhost");
        response.addCookie(cookie);

        return "forward:/test/map_and_model/success";
    }

    @ResponseBody
    @GetMapping("/test/map_and_model/success")
    public Object success(HttpServletRequest request,
                          @CookieValue("uid") Cookie cookie) {
        HashMap<String, Object> content = new HashMap<>();
        content.put("name", request.getAttribute("name"));
        content.put("age", request.getAttribute("age"));
        content.put("gender", request.getAttribute("gender"));
        content.put("cookie", cookie);
        return content;
    }
}
